package com.meritit.portal.SsoSystem.service;

import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.meritit.portal.SsoSystem.bean.SsoSystem;
import com.meritit.portal.util.DBConnection;
import com.meritit.portal.util.ListContainer;
import com.meritit.portal.util.PageAction;

/**
 * 公司: 西安美林电子有限责任公司 
 * 作者：xuejp，Nov 29, 2011 10:11:57 AM 
 * 修改：zhangxh 2014-09-04
 * 描述：业务入口,业务层接口实现类 
 * 说明: 业务层接口实现类
 */
public class SsoSystemMgr implements ISsoSystemMgr {

	private static Logger log = Logger.getLogger(SsoSystemMgr.class);

	/**
	 * 查询业务系统配置列表
	 * 
	 * @return
	 */
	public ListContainer configList(int currentPageInt, int itemsInPage,
			String action, int jumpPage) throws Exception {
		ListContainer lc = new ListContainer();
		lc.setCurrentPage(currentPageInt); // 设置分页前的当前页码
		lc.setItemsInPage(itemsInPage); // 设置每页可显示的记录数
		lc.setPageAction(PageAction.fromString(action));// 设置分页行为，默认时为去首页
		lc.setJumpIndex(jumpPage); // 设置跳页的目标页码，如果分页行为不是跳页的话会忽略它
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		List<SsoSystem> list = new ArrayList<SsoSystem>();
		try {
			conn = DBConnection.getConn();
			String sql = "select t.be_id, t.be_short_name, t.be_summary, t.be_code, " +
					"t.login_url, t.be_order, t.is_show, t.be_full_name, t.cb_ws_enable, " +
					"t.cb_ws_url, t.cb_ws_namespace, t.ispublic, t.image_name " +
					"from PORTAL_BUSINESS_ENTRY t order by t.be_order";
			stmt = conn.prepareStatement("select count(t.be_id) from PORTAL_BUSINESS_ENTRY t");
			rs = stmt.executeQuery();// 执行查询语句
			if (rs.next()) {
				lc.setTotalItem(rs.getInt(1)); // 设置记录总数
			}
			stmt = conn.prepareStatement(sql,
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY);
			int nextFirstIndex = lc.calculateNextPageIndex();
			stmt.setMaxRows(nextFirstIndex + itemsInPage);
			rs = stmt.executeQuery();// 执行查询语句
			rs.first();
			// 游标移动到要输出的第一条记录
			rs.relative(nextFirstIndex - 1);
			while (rs.next()) {
				SsoSystem system = new SsoSystem();
				system.setId(rs.getString("BE_ID"));
				system.setShortName(rs.getString("BE_SHORT_NAME"));
				system.setLoginUrl(rs.getString("LOGIN_URL"));
				system.setFullName(rs.getString("BE_FULL_NAME"));
				system.setCode(rs.getString("BE_CODE"));
				system.setIsShow(rs.getString("IS_SHOW"));
				system.setCbWsUrl(rs.getString("CB_WS_URL"));
				system.setCbWsEnable(rs.getString("CB_WS_ENABLE"));
				system.setCbWsNameSpace(rs.getString("CB_WS_NAMESPACE"));
				system.setSummary(rs.getString("BE_SUMMARY"));
				system.setOrder(rs.getInt("BE_ORDER"));
				system.setIsPublic(rs.getString("ISPUBLIC"));
				system.setImageName(rs.getString("IMAGE_NAME"));
				list.add(system);
			}
			lc.setList(list);
		} catch (Exception e) {
			log.error("查询业务系统信息出错,出错原因:" + e.getMessage());
			throw e;
		} finally {
			if (rs != null) {
				rs.close();
			}
			if (stmt != null) {
				stmt.close();
			}
			DBConnection.realseCon(conn);
		}
		return lc;
	}

	/**
	 * 查询图标库图标
	 * 
	 * @return
	 */
	public List<String> imgList() throws Exception {
		List<String> list = new ArrayList<String>();
		try {
			String path = ServletActionContext.getServletContext().getRealPath(
					"/img/icons");
			File file = new File(path);
			File[] subFile = file.listFiles();
			for (int i = 0; i < subFile.length; i++) {
				String filename = subFile[i].getName();
				list.add(filename);
			}
		} catch (Exception e) {
			log.error("查询图标库图标信息出错,出错原因:" + e.getMessage(), e);
			throw e;
		}
		return list;
	}

	/**
	 * 新增业务系统信息
	 * 
	 * @return
	 */
	public void configAdd(SsoSystem system) throws Exception {
		Connection con = null;
		PreparedStatement prep = null;
		try {
			String sql = "insert into PORTAL_BUSINESS_ENTRY (BE_ID, BE_SUMMARY, BE_SHORT_NAME, " +
					"BE_CODE, LOGIN_URL, BE_ORDER, IS_SHOW, BE_FULL_NAME, CB_WS_ENABLE, CB_WS_URL, " +
					"CB_WS_NAMESPACE, ISPUBLIC, IMAGE_NAME, ZD_WS_URL, ZD_WS_NAMESPACE) values " +
					"(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
			con = DBConnection.getConn();
			con.setAutoCommit(false);
			int order = this.getOrder(con);
			prep = con.prepareStatement(sql);
			prep.setString(1, system.getId());
			prep.setString(2, system.getSummary());
			prep.setString(3, system.getShortName());
			prep.setString(4, system.getCode());
			prep.setString(5, system.getLoginUrl());
			prep.setInt(6, order);
			prep.setString(7, system.getIsShow());
			prep.setString(8, system.getFullName());
			prep.setString(9, system.getCbWsEnable());
			prep.setString(10, system.getCbWsUrl());
			prep.setString(11, system.getCbWsNameSpace());
			prep.setString(12, system.getIsPublic());
			prep.setString(13, system.getImageName());
			prep.setString(14, system.getZdWsUrl());
			prep.setString(15, system.getZdWsNameSpace());
			
			prep.executeUpdate();
			con.commit();
		} catch (Exception e) {
			con.rollback();
			log.error("新增业务系统信息出错,出错原因:" + e.getMessage(), e);
			throw e;
		} finally {
			if (prep != null) {
				prep.close();
			}
			DBConnection.realseCon(con);
		}
	}

	/**
	 * 查询业务系统信息
	 * 
	 * @return
	 */
	public SsoSystem queryById(String id) throws Exception {
		Connection con = null;
		PreparedStatement prep = null;
		ResultSet rs = null;
		SsoSystem system = new SsoSystem();
		try {
			con = DBConnection.getConn();
			String sql = "select t.be_id, t.be_short_name, t.be_summary, t.be_code, " +
					"t.login_url, t.be_order, t.is_show, t.be_full_name, t.cb_ws_enable, " +
					"t.cb_ws_url, t.cb_ws_namespace, t.ispublic, t.image_name,t.ZD_WS_URL,t.ZD_WS_NAMESPACE " +
					"from PORTAL_BUSINESS_ENTRY t where t.be_id = ?";
			prep = con.prepareStatement(sql);
			prep.setString(1, id);
			rs = prep.executeQuery();// 执行查询语句
			if (rs.next()) {
				system.setId(rs.getString("BE_ID"));
				system.setShortName(rs.getString("BE_SHORT_NAME"));
				system.setLoginUrl(rs.getString("LOGIN_URL"));
				system.setFullName(rs.getString("BE_FULL_NAME"));
				system.setCode(rs.getString("BE_CODE"));
				system.setIsShow(rs.getString("IS_SHOW"));
				system.setCbWsUrl(rs.getString("CB_WS_URL"));
				system.setCbWsEnable(rs.getString("CB_WS_ENABLE"));
				system.setCbWsNameSpace(rs.getString("CB_WS_NAMESPACE"));
				system.setSummary(rs.getString("BE_SUMMARY"));
				system.setOrder(rs.getInt("BE_ORDER"));
				system.setIsPublic(rs.getString("ISPUBLIC"));
				system.setImageName(rs.getString("IMAGE_NAME"));
				system.setZdWsUrl(rs.getString("ZD_WS_URL"));
				system.setZdWsNameSpace(rs.getString("ZD_WS_NAMESPACE"));
			}
			return system;
		} catch (Exception e) {
			log.error("查询业务系统信息出错,出错原因:" + e.getMessage(), e);
			throw e;
		} finally {
			if (rs != null) {
				rs.close();
			}
			if (prep != null) {
				prep.close();
			}
			DBConnection.realseCon(con);
		}
	}

	/*
	 * (non-Javadoc)
	 * @see com.meritit.portal.SsoSystem.service.ISsoSystemMgr#configUpdate(com.meritit.portal.SsoSystem.bean.SsoSystem)
	 */
	public void configUpdate(SsoSystem system) throws Exception {
		Connection con = null;
		PreparedStatement prep = null;
		try {
			String sql = "update PORTAL_BUSINESS_ENTRY t set t.BE_SUMMARY = ?, t.BE_SHORT_NAME = ?, " +
					"t.BE_CODE = ?, t.LOGIN_URL = ?, t.IS_SHOW = ?, t.BE_FULL_NAME = ?, t.CB_WS_ENABLE = ?, " +
					"t.CB_WS_URL = ?, t.CB_WS_NAMESPACE = ?, t.ISPUBLIC = ?, t.IMAGE_NAME = ?, t.ZD_WS_URL = ?, " +
					"t.ZD_WS_NAMESPACE = ? where t.BE_ID = ?";
			con = DBConnection.getConn();
			con.setAutoCommit(false);
			prep = con.prepareStatement(sql);
			prep.setString(1, system.getSummary());
			prep.setString(2, system.getShortName());
			prep.setString(3, system.getCode());
			prep.setString(4, system.getLoginUrl());
			prep.setString(5, system.getIsShow());
			prep.setString(6, system.getFullName());
			prep.setString(7, system.getCbWsEnable());
			prep.setString(8, system.getCbWsUrl());
			prep.setString(9, system.getCbWsNameSpace());
			prep.setString(10, system.getIsPublic());
			prep.setString(11, system.getImageName());
			prep.setString(12, system.getZdWsUrl());
			prep.setString(13, system.getZdWsNameSpace());
			prep.setString(14, system.getId());
			prep.executeUpdate();
			con.commit();
		} catch (Exception e) {
			con.rollback();
			log.error("修改业务系统信息出错,出错原因:" + e.getMessage(), e);
			throw e;
		} finally {
			if (prep != null) {
				prep.close();
			}
			DBConnection.realseCon(con);
		}
	}

	/*
	 * (non-Javadoc)
	 * @see com.meritit.portal.SsoSystem.service.ISsoSystemMgr#configDel(java.lang.String)
	 */
	public void configDel(String id) throws Exception {
		Connection conn = null;
		Statement stmt = null;
		try {
			conn = DBConnection.getConn();
			conn.setAutoCommit(false);
			stmt = conn.createStatement();
			// 拼接sql语句
			String[] ids = id.split(";");
			for (int i = 0; i < ids.length; i++) {
				if (!"".equals(ids[i])) {
					// 删除该系统常用业务定制数据
					String delCostomFunctionSql = "delete from PORTAL_FUNCTION_CUSTOMIZE t where t.be_id = '"
							+ ids[i] + "'";
					stmt.addBatch(delCostomFunctionSql);
					// 删除该系统业务入口定制数据
					String delSysSql = "delete from PORTAL_USER_BE t where t.be_id = '"
							+ ids[i] + "'";
					stmt.addBatch(delSysSql);
					// 删除该系统专业链接维护数据
					String delLinkSql = "delete from PORTAL_OPER_CATE t where t.be_id = '"
							+ ids[i] + "'";
					stmt.addBatch(delLinkSql);
					// 删除业务系统注册信息
					String sql = "delete from PORTAL_BUSINESS_ENTRY t where t.be_id = '"
							+ ids[i] + "'";
					stmt.addBatch(sql);
				}
			}
			stmt.executeBatch();// 执行语句
			conn.commit();
		} catch (Exception e) {
			conn.rollback();
			log.error("删除业务系统信息出错,出错原因:" + e.getMessage(), e);
			throw e;
		} finally {
			if (stmt != null) {
				stmt.close();
			}
			DBConnection.realseCon(conn);
		}
	}

	/*
	 * (non-Javadoc)
	 * @see com.meritit.portal.SsoSystem.service.SsoSystemMgrIntfs#checkAppCode(java.lang.String, java.lang.String)
	 */
	public int checkAppCode(String beCode, String beId) throws Exception {
		Connection con = null;
		PreparedStatement prep = null;
		ResultSet rs = null;
		int rows = 0;
		try {
			String sql = "select count(*) from portal_business_entry t where t.be_code =  ?";
			if (beId != null) {
				sql = "select count(*) from portal_business_entry t where t.be_code =  ? and t.be_id != ?";
			}
			con = DBConnection.getConn();
			prep = con.prepareStatement(sql);
			prep.setString(1, beCode);
			if (beId != null) {
				prep.setString(2, beId);
			}
			rs = prep.executeQuery();
			if (rs.next()) {
				rows = rs.getInt(1);
			}
		} catch (Exception e) {
			log.error("校验业务系统编码是否重复出错,出错原因:" + e.getMessage(), e);
			throw e;
		} finally {
			if (rs != null) {
				rs.close();
			}
			if (prep != null) {
				prep.close();
			}
			DBConnection.realseCon(con);
		}
		return rows;
	}
	
	/**
	 * 查询数据表中的排序号
	 * @param con
	 * @return
	 * @throws Exception
	 */
	private int getOrder(Connection con) throws Exception {
		int order = 1;
		PreparedStatement prep = null;
		ResultSet rs = null;
		try {
			String sql = "select count(t.be_id) + 1 from PORTAL_BUSINESS_ENTRY t";
			prep = con.prepareStatement(sql);
			rs = prep.executeQuery();
			if (rs.next()) {
				order = rs.getInt(1);
			}
		} catch (Exception e) {
			log.error("查询数据表中的排序号出错,出错原因:" + e.getMessage(), e);
		} finally {
			if (rs != null && !rs.isClosed()) {
				rs.close();
			}
			if (prep != null && !prep.isClosed()) {
				prep.close();
			}
		}
		return order;
	}
}
